/**
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ECMASCRIPT_HANDLE_STORAGE_CHECK_H
#define ECMASCRIPT_HANDLE_STORAGE_CHECK_H

#include "plugins/ecmascript/runtime/js_thread.h"

namespace ark::ecmascript {

#ifndef NDEBUG
constexpr bool IS_HANDLE_STORAGE_ALLOW_CHECK = true;
#else
constexpr bool IS_HANDLE_STORAGE_ALLOW_CHECK = false;
#endif  // NDEBUG

template <bool IS_DEBUG = IS_HANDLE_STORAGE_ALLOW_CHECK>
class HandleStorageCheckT {
public:
    explicit HandleStorageCheckT(JSThread *thread)
    {
        (void)thread;
    }

    NO_COPY_SEMANTIC(HandleStorageCheckT);
    NO_MOVE_SEMANTIC(HandleStorageCheckT);

    ~HandleStorageCheckT() = default;
};

template <>
class HandleStorageCheckT<true> {
public:
    explicit HandleStorageCheckT(JSThread *thread)
        : thread_(thread), handleStorageCheck_(thread->GetHandleScopeStorageNext())
    {
    }

    ~HandleStorageCheckT()
    {
        (void)thread_;
        (void)handleStorageCheck_;
        ASSERT(handleStorageCheck_ == thread_->GetHandleScopeStorageNext());
    }

    NO_COPY_SEMANTIC(HandleStorageCheckT);
    NO_MOVE_SEMANTIC(HandleStorageCheckT);

private:
    JSThread *thread_;
    JSTaggedType *handleStorageCheck_;
};

using HandleStorageCheck = HandleStorageCheckT<IS_HANDLE_STORAGE_ALLOW_CHECK>;

}  // namespace ark::ecmascript
#endif  // ECMASCRIPT_HANDLE_STORAGE_CHECK_H
